"use strict";

Object.defineProperty(exports, "__esModule", {
	value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * 任务类
 * new Task({
	run() {
		console.log(this.count);
		return {
			success: this.count >= 3,
			data: "" + this.count
		};
	},
	delay: 1000,
	retry: 5,
	interval: 5000
});
 *run:为要执行的函数；返回值success是判断执行是否成功的标志，data为返回数据；
 *delay:延迟多少ms执行
 *interval:两次执行的间隔ms
 *retry:失败时重试的次数
 */
var Task = exports.Task = function Task(_ref) {
	var run = _ref.run,
	    delay = _ref.delay,
	    retry = _ref.retry,
	    interval = _ref.interval;

	_classCallCheck(this, Task);

	this.run = run;
	this.delay = delay;
	this.retry = retry;
	this.interval = interval;
	this.count = 1;
	return this.schedule();
};

/**
 * 调度任务执行方法；出现异常则会直接失败不在重试；
 * @param {*} task 
 * @returns 
 */


Task.prototype.schedule = function () {
	var task = this;
	return new Promise(function (resolve, reject) {
		setTimeout(function () {
			try {
				var result = task.run();
				resolve(result);
			} catch (error) {
				reject(error);
			}
		}, task.count == 0 ? task.delay : task.interval);
	}).then(function (result) {
		if (result.success) {
			return result.data;
		} else {
			if (task.count < task.retry) {
				task.count++;
				return task.schedule();
			} else {
				return result.data;
			}
		}
	});
};

exports.default = {
	Task: Task
};